<template>
  <view class="container">
    <view v-if="loading" class="loading">正在加载...</view>
    <view v-else>
      <view v-if="currentQuestion" class="question-item">
        <text>{{ currentQuestion.title }}</text>
        <view class="answer-options options-column">
          <radio-group @change="radioChange">
            <label class="option" v-for="(option, idx) in ['A', 'B', 'C', 'D']" :key="idx">
              <radio :value="option" :checked="currentQuestion.selected === option" color="#ff0000"/>
              {{ option }}: {{ currentQuestion['answer_' + option.toLowerCase()] }}
            </label>
          </radio-group>
        </view>
        <button @click="submitAnswer">提交答案</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      questions: [], // 存储题库数据的数组
      loading: true, // 控制加载状态
      currentQuestion: null, // 存储当前显示的问题对象
    };
  },
  methods: {
    async fetchQuestions() {
      try {
        const token = await this.getTokenFromFile();

        const url = 'http://106.15.182.86:9099/studylist';
        const headers = {
          'Authorization': token,
          'Content-Type': 'application/json',
          'Host': '106.15.182.86:9099',
          'Connection': 'Keep-Alive',
          'Accept-Encoding': 'gzip'
        };
        const data = {
          query: {
            page: 1,
            size: 10
          }
        };

        uni.request({
          url,
          method: 'POST', // 使用POST方法
          header: headers,
          data: JSON.stringify(data), // 发送的数据，需要序列化
          dataType: 'json', // 指定返回的数据类型
          success: (res) => {
            if (res.statusCode === 200 && res.data && res.data.data && res.data.data.length > 0) {
              // 处理返回的数据，添加一个默认的selected属性
              const processedQuestions = res.data.data.map(question => ({
                ...question,
                selected: '' // 默认没有选项被选中
              }));
              this.questions = processedQuestions;
              this.selectRandomQuestion();
              this.loading = false;
            } else {
              this.loading = false;
              uni.showToast({
                title: '没有更多了',
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: (err) => {
            this.loading = false;
            console.error('请求失败：', err);
          }
        });
      } catch (error) {
        this.loading = false;
        console.error('获取token或请求过程中发生错误：', error);
      }
    },

    // 随机选择一个题目作为当前题目
    selectRandomQuestion() {
      if (this.questions.length > 0) {
        const randomIndex = Math.floor(Math.random() * this.questions.length);
        this.currentQuestion = this.questions[randomIndex];
      } else {
        this.currentQuestion = null;
        uni.showToast({
          title: '没有更多题目了',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 处理选项变化
    radioChange(e) {
      this.currentQuestion.selected = e.detail.value;
      console.log('选择的答案:', this.currentQuestion.selected);
    },

    // 提交答案
    async submitAnswer() {
      if (!this.currentQuestion) return;

      const trueAnswer = parseInt(this.currentQuestion.true_answer, 10);
      const userAnswerNumber = 'ABCD'.indexOf(this.currentQuestion.selected) + 1;

      if (userAnswerNumber === trueAnswer) {
        console.log('回答正确了');
        uni.showToast({
          title: `回答正确`,
          icon: 'none',
          duration: 2000
        });

        try {
          const token = await this.getTokenFromFile();
          await uni.request({
            url: 'http://106.15.182.86:9099/studycorrect',
            method: 'POST',
            header: {
              'Authorization': token,
              'Content-Type': 'application/json',
              'Host': '106.15.182.86:9099',
              'Connection': 'Keep-Alive',
              'Accept-Encoding': 'gzip'
            },
            data: {},
            success(res) {
              console.log('请求成功:', res.data);
            },
            fail(err) {
              console.error('请求失败:', err);
            }
          });
        } catch (error) {
          console.error('获取token失败:', error);
        }
      } else {
        console.log('回答错误，正确答案是:', trueAnswer);
        uni.showToast({
          title: `回答错误`,
          icon: 'none',
          duration: 2000
        });

        try {
          const token = await this.getTokenFromFile();
          await uni.request({
            url: 'http://106.15.182.86:9099/studyerror',
            method: 'POST',
            header: {
              'Authorization': token,
              'Content-Type': 'application/json',
              'Host': '106.15.182.86:9099',
              'Connection': 'Keep-Alive',
              'Accept-Encoding': 'gzip'
            },
            data: {},
            success(res) {
              console.log('请求成功:', res.data);
            },
            fail(err) {
              console.error('请求失败:', err);
            }
          });
        } catch (error) {
          console.error('获取token失败:', error);
        }
      }

      this.selectRandomQuestion();
    },

    // 获取 token
    async getTokenFromFile() {
      const token = uni.getStorageSync('token');
      if (!token) {
        throw new Error('Token not found');
      }
      return token;
    }
  },
  onLoad() {
    this.fetchQuestions(); // 页面加载时获取题库数据
  }
}
</script>

<style scoped>
.container {
  padding: 20upx;
}
.question-item {
  border-bottom: 1px solid #ccc;
  padding: 10upx 0;
}
.answer-options {
  margin-top: 10upx;
}
.options-column {
  display: flex;
  flex-direction: column;
}
.option {
  display: flex;
  align-items: center;
  margin-bottom: 5upx;
}
</style>